package com.zshan.clinic.admin.config;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zshan.clinic.admin.constant.OssProperties;
import com.zshan.clinic.admin.constant.PropertiesUtil;
import com.zshan.clinic.admin.service.config.FileUploadService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * OSS 自动装配类，包含条件判断的内部类
 */
@Configuration
@EnableConfigurationProperties(OssProperties.class)
public class OssAutoConfiguration {

    @Bean
    @Conditional(OssConfiguredCondition.class) // 👈 用内部类做条件判断
    public OSS ossClient(OssProperties properties) {
        return new OSSClientBuilder().build(
                properties.getEndPoint(),
                properties.getAccessKeyId(),
                properties.getAccessKeySecret()
        );
    }

    @Bean
    @ConditionalOnBean(OSS.class) // 只有 OSS 成功注入时才注入上传服务
    public FileUploadService fileUploadService(OSS ossClient, OssProperties properties, PropertiesUtil propertiesUtil) {
        return new FileUploadService(ossClient, properties,propertiesUtil);
    }

    /**
     * 内部类：判断配置是否齐全
     */
    static class OssConfiguredCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            try {
                Binder binder = Binder.get(context.getEnvironment());
                OssProperties props = binder.bind("oss", Bindable.of(OssProperties.class)).orElse(null);
                return props != null && props.isValid();
            } catch (Exception e) {
                return false;
            }
        }
    }
}
